﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NServiceBus;
using Framework.Infrastructure;
using Framework.Config;
using System.Transactions;
using Framework.Bus.LifetimeManagers;

namespace Framework.Bus
{
    public class CommandHandler : IHandleMessages<Framework.Command.ICommand>
    {
        public IBus Bus { get; set; }
        public IMessageDispatcher MessageDispatcher { get; set; }

        #region IMessageHandler<IDomainEvent> Members

        public void Handle(Framework.Command.ICommand message)
        {
            try
            {
                using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    MessageDispatcher.DispatchMessage(message);
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                Bus.Reply(ex.GetRescureInnerException().Message);
            }
            finally
            {
                Bus.CurrentMessageContext.ClearItems();
            }
        }

        #endregion
    }
}
